package dyyx.util;

import java.util.HashMap;
import java.util.Map;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import dyyx.dto.JmxClient;

public abstract class JmxClientUtil {
	
	private static volatile JmxClient client;
	
	
	public static synchronized JmxClient getClient()throws Exception{
		if(client==null){
			throw new Exception("not connected"); 
		}
		return client;
	}
	
	public static synchronized void connect(String connstr)throws Exception{
		if(client!=null){
			throw new Exception("connected"); 
		}
		String url = "service:jmx:rmi:///jndi/rmi://"+connstr+"/jmxrmi";
		JMXServiceURL serviceURL = new JMXServiceURL(url);  
		JMXConnector conn = JMXConnectorFactory.connect(serviceURL);  
		MBeanServerConnection mbconn = conn.getMBeanServerConnection();  
		
		JmxClient clienttmp = new JmxClient(conn,mbconn,null,connstr);
		client = clienttmp;			
	}
	
	
	public static synchronized void disconnect()throws Exception{
		if(client==null){
			throw new Exception("not connected"); 
		}
		client.close();
		client = null;
	}
	
	

	
	
	
	
	
	public static synchronized Map<String,Object> getClientInfo()throws Exception{
		if(client==null){
			throw new Exception("not connected"); 
		}
		
		Map<String,Object> map = new HashMap<>();
		map.put("connectString", client.connectString);
		map.put("createTime", client.createTime);
	
		return map;
	}
	

}
